﻿using ShopWebAPI.log4netConfig;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web;
using System.Web.Http.Filters;
using WebShopAPI.Models;
using System.IO;
namespace WebShopAPI.Filter
{
    /// <summary>
    ///  异常过滤器类，继承  ExceptionFilterAttribute 
    /// </summary>
    public class CustomExceptionAttribute : ExceptionFilterAttribute
    {
         Logger _logger = new Logger(typeof(CustomExceptionAttribute));
        /// <summary>
        /// 方法会在出现异常时触发  
        /// 1 日志一下
        /// </summary>
        /// <param name="actionExecutedContext"></param>
        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            //Console.WriteLine($"{actionExecutedContext.Request.RequestUri.AbsoluteUri}:{actionExecutedContext.Exception.Message}");
            //1.异常日志记录（正式项目里面一般是用log4net记录异常日志）
            //Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "——" +
            //    actionExecutedContext.Exception.GetType().ToString() + "：" + actionExecutedContext.Exception.Message + "——堆栈信息：" +
            //    actionExecutedContext.Exception.StackTrace);

            ////记录到文本文件中
            //System.IO.File.AppendAllText("C:\\22222.txt",
            //    DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "——" +
            //    actionExecutedContext.Exception.GetType().ToString() + "："
            //    + actionExecutedContext.Exception.Message + "——堆栈信息：" +
            //    actionExecutedContext.Exception.StackTrace);

          //  _logger.Error(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "发生错误", actionExecutedContext.Exception);
           // File.AppendAllText(@"C:\error.txt", "发生错误:" + actionExecutedContext.Exception);
            //把当前请求的返回指定一下
            actionExecutedContext.Response = actionExecutedContext.Request.CreateResponse(
                 HttpStatusCode.OK,
                new ResponData
                {
                    data = null,
                    meta = new Meta
                    {
                        msg = "出现问题请联系管理员",
                        status = 500 //
                    }
                  
                });

           // base.OnException(actionExecutedContext);
        }
    }
}